/*
 * Copyright 2020-2021 redragon.dongbin
 *
 * This file is part of redragon-erp/赤龙ERP.

 * redragon-erp/赤龙ERP is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.

 * redragon-erp/赤龙ERP is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with redragon-erp/赤龙ERP.  If not, see <https://www.gnu.org/licenses/>.
 */
package com.global.controller;

import com.activiti.dao.service.ActivitiService;
import com.erp.finance.ap.invoice.service.ApInvoiceHeadService;
import com.erp.finance.ar.invoice.service.ArInvoiceHeadService;
import com.erp.finance.voucher.service.FinVoucherHeadService;
import com.erp.hr.base.util.CommonUtils;
import com.erp.hr.dao.model.HrDepartment;
import com.erp.hr.dao.model.HrStaffDepartmentVO;
import com.erp.hr.dao.model.HrStaffInfoRO;
import com.erp.hr.service.HrCommonService;
import com.erp.masterdata.customer.service.MdCustomerService;
import com.erp.masterdata.vendor.dao.model.MdVendor;
import com.erp.masterdata.vendor.service.MdVendorService;
import com.erp.order.po.service.PoHeadService;
import com.erp.order.so.service.SoHeadService;
import com.erp.permission.service.SysUserService;
import com.global.util.GiteeUtil;
import org.redragon.commons.lang.Times;
import org.redragon.framework.util.EhcacheUtil;
import org.redragon.framework.util.JsonDataUtil;
import org.redragon.framework.util.RedisUtil;
import org.redragon.framework.util.ShiroUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.sun.media.jfxmedia.logging.Logger;

import static com.erp.hr.base.util.CommonUtils.VENDORROLEID;

/**
 * @description
 * @date 2020年6月26日
 * @author dongbin
 * 
 */
@Controller
public class GlobalController {
    
    //服务类
    @Autowired
    private HrCommonService hrCommonService;
    @Autowired
    private FinVoucherHeadService finVoucherHeadService;
    @Autowired
    private ApInvoiceHeadService apInvoiceHeadService;
    @Autowired
    private ArInvoiceHeadService receiptHeadService;
    @Autowired
    private PoHeadService poHeadService;
    @Autowired
    private SoHeadService soHeadService;
    @Autowired
    private MdCustomerService mdCustomerService;
    @Autowired
    private MdVendorService mdVendorService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private ActivitiService activitiService;
    
    
    @RequestMapping("error404")
    public String error404() {
        return "/common/error/404";
    }
    
    @RequestMapping("apiError404")
    @ResponseBody
    public String apiError404() {
        return JsonDataUtil.getExecuteJson(-1, "404");
    }
    
    @RequestMapping("error500")
    public String error500() {
        return "/common/error/500";
    }
    
    @RequestMapping("web/main")
    public String webMain(Model model, HttpSession session, HttpServletRequest request) {
        //获取当前用户职员信息
        HrStaffInfoRO staffInfo = this.hrCommonService.getStaffInfo(ShiroUtil.getPrincipal());
        //如果当前部门为供应商所在的部门则直接返回供应商信息
        HrDepartment hrDepartmentget=new HrDepartment();
        if(CommonUtils.lxr.equals(staffInfo.getDepartmentCode())){
            MdVendor mdVendor=this.mdVendorService.getDataByCredictCode(ShiroUtil.getPrincipal());
            staffInfo.setCompanyName(mdVendor.getVendorName());
        }
        else{
            hrDepartmentget=this.hrCommonService.getHrDepartmentParentCompany(staffInfo.getDepartmentCode());
            staffInfo.setCompanyName(hrDepartmentget.getDepartmentName());
            staffInfo.setCompanyCode(hrDepartmentget.getDepartmentCode());
        }
        Times time = new Times();
        String startDate = time.getDate()+" 00:00:00";
        String endDate = time.getDate()+" 23:59:59";
        //获取采购订单数
        model.addAttribute("poHeadNum", this.poHeadService.getPoHeadNum(startDate, endDate));
        //获取销售订单数
        model.addAttribute("soHeadNum", this.soHeadService.getSoHeadNum(startDate, endDate));
        //获取付款单数
        model.addAttribute("payHeadNum", this.apInvoiceHeadService.getApInvoiceHeadNum(startDate, endDate));
        //获取收款单数
        model.addAttribute("receiptHeadNum", this.receiptHeadService.getArInvoiceHeadNum(startDate, endDate));
        //获取凭证数
        model.addAttribute("voucherHeadNum", this.finVoucherHeadService.getVoucherHeadNum(startDate, endDate));
        //获取客户数
        model.addAttribute("customerNum", this.mdCustomerService.getCustomerNum());
        //获取供应商数
        model.addAttribute("vendorNum", this.mdVendorService.getVendorNum());
        //获取首页代办任务
        model.addAttribute("taskList", this.activitiService.queryTaskInfo(this.activitiService.erpFindPersonalTaskList(staffInfo)));
        //获取代办已办统计数据
        model.addAttribute("taskCount", this.activitiService.queryTaskCount(staffInfo.getStaffCode()));
        //页面属性设置
        model.addAttribute("staffInfo", staffInfo);
        session.setAttribute("staffInfo", staffInfo);
        String userAgent = request.getHeader( "USER-AGENT" ).toLowerCase();
        //判断用户身份是否为代理商 如果是直接跳到代理商页面
        ShiroUtil.isPermittedAnyPerm("admin");
        if(checkVendor(ShiroUtil.getRoles())){
            return "basic.jsp?content=vendorMain";
        }
        //判断是否是手机端登录
        if(checkMobile(userAgent)){
            return "pda/index";
        }
        else{
            return "basic.jsp?content=main";
        }

    }
    @RequestMapping("pda/main")
    public String pdaMain(Model model, HttpSession session, HttpServletRequest request) {
        //获取当前用户职员信息
        HrStaffInfoRO staffInfo = this.hrCommonService.getStaffInfo(ShiroUtil.getPrincipal());
        HrDepartment hrDepartmentget=this.hrCommonService.getHrDepartmentParentCompany(staffInfo.getDepartmentCode());
        staffInfo.setCompanyName(hrDepartmentget.getDepartmentName());
        staffInfo.setCompanyCode(hrDepartmentget.getDepartmentCode());
        Times time = new Times();
        String startDate = time.getDate()+" 00:00:00";
        String endDate = time.getDate()+" 23:59:59";
        //获取采购订单数
        model.addAttribute("poHeadNum", this.poHeadService.getPoHeadNum(startDate, endDate));
        //获取销售订单数
        model.addAttribute("soHeadNum", this.soHeadService.getSoHeadNum(startDate, endDate));
        //获取付款单数
        model.addAttribute("payHeadNum", this.apInvoiceHeadService.getApInvoiceHeadNum(startDate, endDate));
        //获取收款单数
        model.addAttribute("receiptHeadNum", this.receiptHeadService.getArInvoiceHeadNum(startDate, endDate));
        //获取凭证数
        model.addAttribute("voucherHeadNum", this.finVoucherHeadService.getVoucherHeadNum(startDate, endDate));
        //获取客户数
        model.addAttribute("customerNum", this.mdCustomerService.getCustomerNum());
        //获取供应商数
        model.addAttribute("vendorNum", this.mdVendorService.getVendorNum());
        //获取首页代办任务
        model.addAttribute("taskList", this.activitiService.queryTaskInfo(this.activitiService.erpFindPersonalTaskList(staffInfo)));
        //获取代办已办统计数据
        model.addAttribute("taskCount", this.activitiService.queryTaskCount(staffInfo.getStaffCode()));
        //页面属性设置
        model.addAttribute("staffInfo", staffInfo);
        session.setAttribute("staffInfo", staffInfo);
        return "pda/index";
    }
    @RequestMapping("phone/main")
    public String phoneMain(Model model, HttpSession session) {

        //获取当前用户职员信息
        HrStaffInfoRO staffInfo = this.hrCommonService.getStaffInfo(ShiroUtil.getPrincipal());
        //页面属性设置
        model.addAttribute("staffInfo", staffInfo);
        session.setAttribute("staffInfo", staffInfo);
        return "pda/index.jsp";
    }

    public void testActiviti(){
        //2.得到RunService对象
//        RuntimeService runtimeService = processEngine.getRuntimeService();
//
//        //3.创建流程实例  流程定义的key需要知道 holiday
//        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("key");
//
//        //4.输出实例的相关信息
//        System.out.println("流程部署ID"+processInstance.getDeploymentId());//null
//        System.out.println("流程定义ID"+processInstance.getProcessDefinitionId());//holiday:1:4
//        System.out.println("流程实例ID"+processInstance.getId());//2501
//        System.out.println("活动ID"+processInstance.getActivityId());//null
    }
    @RequestMapping("web/left")
    @ResponseBody
    public String webLeft(Model model, HttpSession session) {
        ShiroUtil.isPermittedAnyPerm("admin");
        String perms = ShiroUtil.getPerms().toString();
        return perms;
    }
    
    @RequestMapping("main")
    public String main() {
        return "redirect: web/main";
    }
    
    @RequestMapping("index")
    public String index() {
        return "redirect: main";
    }
    
    @RequestMapping("")
    public String root() {
        return "redirect: index";
    }
    
    @RequestMapping("web/main/clearCache")
    @ResponseBody
    public String clearCache() {
        try{
            //清除缓存ehcache、redis
            EhcacheUtil.clearCacheBatch("DATASET_*");
            RedisUtil.clearCacheBatch("DATASET_*");
            
            EhcacheUtil.clearCacheBatch("MD_*");
            RedisUtil.clearCacheBatch("MD_*");
            
            EhcacheUtil.clearCacheBatch("GL_*");
            RedisUtil.clearCacheBatch("GL_*");
            
            EhcacheUtil.clearCacheBatch("com.erp*");
            RedisUtil.clearCacheBatch("com.erp*");
            
            return JsonDataUtil.getExecuteJson(0);
        }catch(Exception e) {
            return JsonDataUtil.getExecuteJson(-1, "清除缓存失败");
        }
    }
    
    
    
    /**
     * 
     * @description 验证星标
     * @date 2021年2月5日
     * @author dongbin
     * @return void
     *
     */
    @RequestMapping("web/main/validateData")
    public void validateGiteeStar() {
        //验证星标
        boolean starFlag = GiteeUtil.isClickStar(ShiroUtil.getPrincipal());
        if(!starFlag) {
            this.sysUserService.updateSysUserStatus(ShiroUtil.getPrincipal(), "N");
        }
        System.out.println("===================######"+ShiroUtil.getPrincipal()+":"+starFlag);
    }
    String phoneReg = "\\b(ip(hone|od)|android|opera m(ob|in)i"
            +"|windows (phone|ce)|blackberry"
            +"|s(ymbian|eries60|amsung)|p(laybook|alm|rofile/midp"
            +"|laystation portable)|nokia|fennec|htc[-_]"
            +"|mobile|up.browser|[1-4][0-9]{2}x[1-4][0-9]{2})\\b";
    String tableReg = "\\b(ipad|tablet|(Nexus 7)|up.browser"
            +"|[1-4][0-9]{2}x[1-4][0-9]{2})\\b";
    Pattern phonePat = Pattern.compile(phoneReg, Pattern.CASE_INSENSITIVE);
    Pattern tablePat = Pattern.compile(tableReg, Pattern.CASE_INSENSITIVE);

    public boolean checkMobile(String userAgent){
        if(null == userAgent){
            userAgent = "";
        }
        // 匹配
        Matcher matcherPhone = phonePat.matcher(userAgent);
        Matcher matcherTable = tablePat.matcher(userAgent);
        if(matcherPhone.find() || matcherTable.find()){
            return true;
        } else {
            return false;
        }
    }
    public boolean checkVendor(Set<String> role){
        for (String roleInfo : role) {
            if(VENDORROLEID.equals(roleInfo)){
                return true;
            }
        }
        return false;
    }
}
